package com.example.game.app.controller;

import com.example.game.app.util.JwtTokenUtil;
import com.example.game.module.dto.LoginDTO;
import com.example.game.module.dto.RegisterDTO;
import com.example.game.module.entity.User;
import com.example.game.module.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestParam String phone,
                                         @RequestParam String password,
                                         @RequestParam String name,
                                         @RequestParam String avatar) {
        try {
            userService.register(phone, password, name, avatar);
            return ResponseEntity.ok("注册成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String,Object>> login(@RequestParam(name = "phone")String phone,
                                            @RequestParam(name = "password") String password) {
        try {
            User user = userService.login(phone, password);
            String token = jwtTokenUtil.generateToken(user);

            if (!jwtTokenUtil.validateToken(token)) {
                throw new RuntimeException("生成的Token无效");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("message", "登录成功");
            result.put("token", token);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
}
